package com.qdc.datacenters.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.qdc.datacenters.client.ChatMsgAuditClient;
import com.qdc.datacenters.client.CorpCustomerClient;
import com.qdc.datacenters.domain.entity.CorpGroup;
import com.qdc.datacenters.domain.entity.CorpGroupMember;
import com.qdc.datacenters.domain.entity.QwGroupMember;
import com.qdc.datacenters.domain.query.chatmsg.ChatMsgListQuery;
import com.qdc.datacenters.domain.query.qw.QwGroupDetailQuery;
import com.qdc.datacenters.domain.query.qw.QwMsgAuditQuery;
import com.qdc.datacenters.domain.vo.chatmsg.ChatMsgRoomListVo;
import com.qdc.datacenters.domain.vo.group.CorpGroupMemberVo;
import com.qdc.datacenters.domain.vo.group.CorpGroupVo;
import com.qdc.datacenters.domain.vo.qw.QwGroupDetailVo;
import com.qdc.datacenters.domain.vo.qw.QwMsgAuditVo;
import com.qdc.datacenters.mapper.CorpGroupMapper;
import com.qdc.datacenters.service.ICorpGroupMemberService;
import com.qdc.datacenters.service.ICorpGroupService;
import com.qdc.datacenters.utils.StrUtils;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;
import java.util.stream.Collectors;

/**
 * 企业微信群(CorpGroup)表服务实现类
 *
 * @author danmo
 * @since 2024-03-04 23:15:33
 */
@Slf4j
@Service
public class CorpGroupServiceImpl extends BaseServiceImpl<CorpGroupMapper, CorpGroup> implements ICorpGroupService {

    @Resource
    private CorpCustomerClient corpCustomerClient;

    @Autowired
    private ICorpGroupMemberService iCorpGroupMemberService;

    @Resource
    private ChatMsgAuditClient auditClient;

    private final ReentrantLock lock = new ReentrantLock();

    @Override
    public CorpGroupVo getByChatId(String chatId) {
        return this.getByChatId(chatId,1);
    }

    @Override
    public CorpGroupVo getByChatId(String chatId, Integer groupType) {
        CorpGroupVo groupInfo = null;
        try {
            if (!lock.tryLock(3, TimeUnit.SECONDS)) {
                return groupInfo;
            }
        } catch (InterruptedException e) {
            log.error("get chat error msg:{}",e.getMessage(),e);
            return groupInfo;
        }
        try {
            groupInfo = this.baseMapper.getByChatId(chatId,groupType);
            if (Objects.isNull(groupInfo)) {
                if(Objects.equals(1,groupType)){
                    QwGroupDetailQuery query = new QwGroupDetailQuery();
                    query.setChat_id(chatId);
                    QwGroupDetailVo groupChatDetail = corpCustomerClient.getGroupChatDetail(query);
                    if (Objects.nonNull(groupChatDetail) && Objects.equals(0, groupChatDetail.getErrCode())) {
                        groupInfo = new CorpGroupVo();
                        CorpGroup corpGroup = new CorpGroup();
                        QwGroupDetailVo.GroupChatDetail groupChat = groupChatDetail.getGroupChat();
                        corpGroup.setChatId(groupChat.getChatId());
                        if(StrUtils.isEmpty(groupChat.getName())){
                            String groupName = groupChat.getMemberList().stream().map(QwGroupMember::getGroupNickName).filter(StrUtils::isNotEmpty).limit(5).collect(Collectors.joining("、"));
                            corpGroup.setGroupName(groupName);
                        }else {
                            corpGroup.setGroupName(groupChat.getName());
                        }
                        corpGroup.setNotice(groupChat.getNotice());
                        corpGroup.setOwner(groupChat.getOwner());
                        corpGroup.setAddTime(new Date(groupChat.getCreateTime() * 1000));
                        String adminUserIds = Optional.ofNullable(groupChat.getAdminList()).orElseGet(null).stream().map(QwGroupDetailVo.WeGroupAdmin::getUserId).collect(Collectors.joining(","));
                        corpGroup.setAdminUserId(adminUserIds);
                        if (save(corpGroup)) {
                            BeanUtils.copyProperties(corpGroup, groupInfo);
                            List<QwGroupMember> memberList = groupChat.getMemberList();
                            if (CollectionUtil.isNotEmpty(memberList)) {
                                List<CorpGroupMember> corpGroupMemberList = memberList.stream().map(member -> {
                                    CorpGroupMember corpGroupMember = new CorpGroupMember();
                                    BeanUtils.copyProperties(member, corpGroupMember);
                                    return corpGroupMember;
                                }).collect(Collectors.toList());
                                if (iCorpGroupMemberService.saveBatch(corpGroupMemberList)) {
                                    List<CorpGroupMemberVo> memberVoList = corpGroupMemberList.stream().map(member -> {
                                        CorpGroupMemberVo corpGroupMemberVo = new CorpGroupMemberVo();
                                        BeanUtils.copyProperties(member, corpGroupMemberVo);
                                        return corpGroupMemberVo;
                                    }).collect(Collectors.toList());
                                    groupInfo.setMemberList(memberVoList);
                                }
                            }
                        }
                    }
                }else if(Objects.equals(2,groupType)){
                    QwMsgAuditQuery auditQuery = new QwMsgAuditQuery();
                    auditQuery.setRoomid(chatId);
                    QwMsgAuditVo msgAuditVo = auditClient.getGroupChat(auditQuery);
                    if (Objects.nonNull(msgAuditVo) && Objects.equals(0, msgAuditVo.getErrCode())) {
                        groupInfo = new CorpGroupVo();
                        CorpGroup corpGroup = new CorpGroup();
                        corpGroup.setChatId(chatId);
                        corpGroup.setGroupName(msgAuditVo.getRoomName());
                        corpGroup.setNotice(msgAuditVo.getNotice());
                        corpGroup.setOwner(msgAuditVo.getCreator());
                        corpGroup.setAddTime(new Date(msgAuditVo.getRoomCreateTime() * 1000));
                        if (save(corpGroup)) {
                            BeanUtils.copyProperties(corpGroup, groupInfo);
                            List<CorpGroupMember> corpGroupMemberList = msgAuditVo.getMembers().stream().map(member -> {
                                CorpGroupMember corpGroupMember = new CorpGroupMember();
                                corpGroupMember.setUserId(member.getMemberId());
                                corpGroupMember.setJoinTime(new Date(member.getJoinTime() * 1000));
                                return corpGroupMember;
                            }).collect(Collectors.toList());
                            iCorpGroupMemberService.saveBatch(corpGroupMemberList);
                        }
                    }
                }
            }
        } catch (Exception e) {
            log.error("get chat error msg:{}",e.getMessage(),e);
            return groupInfo;
        }
        finally {
            lock.unlock();
        }
        return groupInfo;
    }

    @Override
    public List<ChatMsgRoomListVo> getRoomMsgList(ChatMsgListQuery query) {
       return this.baseMapper.getRoomMsgList(query);
    }
}

